package cmd

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/rivo/tview"
	"github.com/spf13/cobra"
	"go-tools/internal/view"
	"os"
	"path/filepath"
)

const (
	ToolName    = "go-tools"
	ToolVersion = "v1.0"
)

func Execute() {
	rootCmd := NewRootCmd()
	if err := rootCmd.Execute(); err != nil {
		PrintErrorWithRed(err)
		os.Exit(-1)
	}
}

func NewRootCmd() *cobra.Command {
	app := &Application{
		Header: tview.NewFlex(),
	}
	var rootCmd = &cobra.Command{
		Use:   fmt.Sprintf("%s [sub_command]", ToolName),
		Short: "made by VisionMind Team",
		RunE: func(cmd *cobra.Command, args []string) error {
			exec, err := os.Executable()
			if err != nil {
				return err
			}
			cmdDir := filepath.Dir(exec)
			print(cmdDir)
			table := view.TableBuilder(clusterInfo())
			app.Header.AddItem(table, LeftWidth, 1, false)
			return nil
		},
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			color.Green("%s now version is: %s", ToolName, ToolVersion)
		},
	}
	return rootCmd
}

func clusterInfo() []string {
	info := []string{
		"Tool Name: " + ToolName,
		"Version: " + ToolVersion,
		"Env: default",
	}
	return info
}

func SetColor(msg string, conf, bg, text int) string {
	return fmt.Sprintf("%c[%d;%d;%dm%s%c[0m", 0x1B, conf, bg, text, msg, 0x1B)
}

func PrintErrorWithRed(err error) {
	fmt.Printf("%s", SetColor(fmt.Sprintf("%+v", err), 0, 0, 31))
}
